package mya.mes.mdc.logic.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class BeanCopy {

    public static void copySrcToDest(Object src, Object dest) {

        Map<String, Field> srcFieldMap = getAllField(src.getClass());
        Map<String, Field> destFieldMap = getAllField(dest.getClass());


        try {
            for (String fieldName : srcFieldMap.keySet()) {
                Field srcField = srcFieldMap.get(fieldName);
                Field destField = destFieldMap.get(fieldName);

                if (srcField == null || destField == null) {
                    continue;
                }
                srcField.setAccessible(true);
                destField.setAccessible(true);

                if (destField != null) {
                    destField.set(dest, srcField.get(src));
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static Map<String, Field> getAllField(Class<?> clz) {

        HashMap<String, Field> map = new HashMap<>(31);

        Class<?> parent = clz;

        int count = 0;

        while (true) {
            if (parent == null) {
                break;
            }
            if (parent == Object.class) {
                break;
            }

            if (count > 5) {
                break;
            }

            Field[] array = parent.getDeclaredFields();

            for (Field field : array) {
                map.put(field.getName(), field);
            }

            parent = parent.getSuperclass();
            count++;
        }

        return map;
    }
}
